<?php

namespace apiend\modules\search\models;

use Yii;
use yii\data\ActiveDataProvider;
use common\helpers\WordMatcher;
use common\helpers\Url;

/**
 * 统一搜索模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class UnifiedSearch extends \common\models\shop\ShopProduct {

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     * @return ActiveDataProvider
     */
    public function search($params = []) {
        $q = isset($params['q']) ? $params['q'] : false;

        $query = static::find()
        ->alias('t')
        ->where([
            't.status' => static::STATUS_ACTIVE,
            't.deleted_at' => 0,
        ]);
        if ($q) {
            $matcher = new WordMatcher();
            $matcher->match($q, $matched);

            if (!empty($matched)) {
                $kids = array_keys($matched);
                $query->joinWith('keywords key');
                $query->andFilterWhere(['key.lib_id' => $kids]);
            } else {
                $keywords = explode(' ', $q);
                if (!empty($keywords)) {
                    $likewhere = ['or'];
                    foreach ($keywords as $word) {
                        $likewhere[] = ['like', 't.name', $word];
                    }
                    $query->andFilterWhere($likewhere);
                }
            }
        }

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'validatePage' => false
            ]
        ]);

//        return \common\helpers\Debug::sql($query);

        return $dataProvider;
    }

    /**
     * 返回检索列表所需的内容
     * return array
     */
    public function fields() {
        return [
            'id',
            'name',
            'thumb' => function() {
                return Url::attach($this->cover);
            },
            'description',
            'price',
            'link' => function () {
                return Url::h5('/goods/' . $this->id);
            },
        ];
    }

}
